package com.teng.mylibrary.base

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.HorizontalScrollView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat.getSystemService
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import com.shehuan.library.StatusView
import com.teng.mylibrary.R
import com.teng.mylibrary.widget.ProTextDialog
import com.teng.mylibrary.widget.ProgressDialog
import org.greenrobot.eventbus.EventBus
import android.view.View.OnTouchListener
import com.teng.mylibrary.util.ToastHelper


/**
 * Description:  BaseFragment
 * Author:       liuteng
 * CreateDate:   2021/11/3 15:33
 * UpdateRemark: 更新说明
 */
abstract class BaseFragment<V : ViewDataBinding, VM : BaseViewModel> : Fragment() {

    protected lateinit var binding: V
    protected lateinit var viewModel: VM
    protected var mActivity: AppCompatActivity? = null
    private val mProgressDialog by lazy {
        ProgressDialog(requireActivity(), R.style.loading_dialog_style)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (isUseEventBus()) {
            if (!EventBus.getDefault().isRegistered(this)) EventBus.getDefault().register(this)
        }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mActivity = context as AppCompatActivity
    }


    @SuppressLint("ClickableViewAccessibility")
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        binding = DataBindingUtil.inflate(
            inflater, initContentView(
                inflater,
                container,
                savedInstanceState
            ), container, false
        )

        //点击空白隐藏软键盘
        binding.root.setOnTouchListener { v, event ->
            val manager =
                requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            if (event.action == MotionEvent.ACTION_DOWN) {
                if (requireActivity().currentFocus != null && requireActivity().currentFocus!!.windowToken != null) {
                    manager.hideSoftInputFromWindow(
                        requireActivity().currentFocus!!.windowToken,
                        InputMethodManager.HIDE_NOT_ALWAYS
                    )
                }
            }
            false
        }
        return binding.root
    }

    fun initStatusView(view: StatusView) {
//        view.setLoadingView(@LayoutRes int layoutId);
//        view.setErrorView(@LayoutRes int layoutId);
        view.setEmptyView(R.layout.empty_view)
        //默认显示空数据布局
//        view.showEmptyView()
        viewModel.uc.showEmptyView.observe(this, {
            view.showEmptyView()
        })
        viewModel.uc.showDataView.observe(this, {
            view.showContentView()
        })
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //私有的初始化Databinding和ViewModel方法
        initViewDataBinding()
        //私有的ViewModel与View的契约事件回调逻辑,
        //fragment跟activity共用一个回调，fragment注释掉
        if (!isShareActivityVModel()) {
            registeredUiChangeLiveDataCallBack()
        }
        //初始化页面控件
        initView()
        //页面数据初始化方法
        initData()

    }

    private fun initViewDataBinding() {
        //获取自定义的viewModel
        viewModel = initViewModel()
        //支持LiveData绑定xml，数据改变，UI自动会更新
        binding.lifecycleOwner = this
        //让ViewModel拥有View的生命周期感应
        lifecycle.addObserver(viewModel)
    }

    private fun registeredUiChangeLiveDataCallBack() {
        //显示加载动画弹框
        viewModel.uc.showDialogEvent.observe(this, {
            mProgressDialog.show()
        })
        //隐藏加载动画弹框
        viewModel.uc.dismissDialogEvent.observe(this, {
            mProgressDialog.dismiss()
        })
        //显示Toast弹框
        viewModel.uc.showToastOkEvent.observe(this, {
            ToastHelper.showOk(mActivity, it)
        })
        //显示Toast弹框
        viewModel.uc.showToastOtherEvent.observe(this, {
            ToastHelper.showOther(mActivity, it)
        })
        //显示单项内容提示
        viewModel.uc.showProTextEvent.observe(this, {
            showProMsg(it)
        })
        //结束当前页
        viewModel.uc.finishPageEvent.observe(this, {
            mActivity!!.finish()
        })

        //结束当前页
        viewModel.uc.hideKeyboard.observe(this, {
            hideInputKeyboard(it)
        })
    }

    /**
     * 隐藏键盘
     * 弹窗弹出的时候把键盘隐藏掉
     */
    protected open fun hideInputKeyboard(v: View) {
        val imm: InputMethodManager =
            mActivity!!.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(v.windowToken, 0)
    }

    open fun bindHeadContentScroll(
        headScrollView: HorizontalScrollView,
        contentScrollView: HorizontalScrollView
    ) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            contentScrollView.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
                headScrollView.scrollTo(scrollX, scrollY)
                true
            }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            headScrollView.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
                contentScrollView.scrollTo(scrollX, scrollY)
                true
            }
        }
    }


    open fun showProMsg(message: String) {
        val dialog = ProTextDialog(message)
        dialog.showNow(childFragmentManager, null)
    }

    protected open fun isShareActivityVModel(): Boolean = false

    protected open fun isUseEventBus(): Boolean = false

    protected abstract fun initViewModel(): VM

    protected abstract fun initView()

    protected abstract fun initData()

    protected abstract fun initContentView(
        inflater: LayoutInflater?,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): Int


    override fun onDestroy() {
        super.onDestroy()
        if (isUseEventBus()) {
            EventBus.getDefault().unregister(this)
        }
    }


}